import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'dart:developer';
import 'dart:core';
//可能用到的异步操作库
import 'dart:async';

/*
提示
个人建议 实例创建 在 initState方法中 ，并且FlutterBlue flutterBlue 声明出来，因为后面操作要用到flutterBlue
*/

class BluePage extends StatefulWidget {
  @override
  _BluePageState createState() => _BluePageState();
}

class _BluePageState extends State<BluePage> {
  late BluetoothDevice device;

  Map<String, ScanResult> scanResults = new Map();
  List allBlueNameAry = [];
  late BluetoothCharacteristic mCharacteristic;
  var flutterBlue = FlutterBlue.instance;

// Start scanning for devices

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //flutterBlue.startScan(timeout: Duration(seconds: 4));

    //flutterBlue.scanResults.listen((scanResult) {
    // Iterate over the scan results
    // for (var result in scanResult) {
    //   // Connect to the device
    //   result.device.connect();
    //
    //   // Discover all services and characteristics of the device
    //   result.device.discoverServices().then((value) {
    //     // Iterate over the services
    //       print("打印监听");
    //       //print(value.toString());
    //       for (int i = 0; i < value.length; i++) {
    //           print(value[i]..toString());
    //       }
    //     // for (var service in value.services) {
    //     //   // Iterate over the characteristics
    //     //   for (var characteristic in service.characteristics) {
    //     //     // Read the value of the characteristic
    //     //     characteristic.read().then((value) {
    //     //       // Do something with the value
    //     //       print(value);
    //     //     });
    //     //   }
    //     // }
    //   });
    // }
    //});
  }

  //开始扫描
  getData() {
    flutterBlue.startScan();
    // 监听扫描结果
    flutterBlue.scanResults.listen((results) {
      setState(() {
        allBlueNameAry = [];
      });
      // 扫描结果 可扫描到的所有蓝牙设备
      for (ScanResult r in results) {
        scanResults[r.device.name] = r;
        //print("r"+r.toString());
        if (r.device.name.length > 0) {
          print("开始-------------------------");
          print("扫描到的设备是:" + r.device.name.toString());
          print("扫描到的设备的uuid是:");
          print('${r.device.name} found! rssi: ${r.rssi}');
          print("结束-------------------------\r\n");
          allBlueNameAry.add(r.device.name);
        }
      }
    });
  }

  //给点特点权限
  //_BleDiscoverServices 方法在5.连接到设备并显示具有特征的服务中调用
  _BleDiscoverServices() async {
    print("连接上GTRS设备...延迟连接");
    await device.connect(autoConnect: false, timeout: Duration(seconds: 10));
    List<BluetoothService> services = await device.discoverServices();
    services.forEach((service) {
      var value = service.uuid.toString();
      print("所有服务值uuid-=-=-=-=-=- --- $value");
      if (service.uuid.toString().contains("00805f9b34fb")) {
        List<BluetoothCharacteristic> characteristics = service.characteristics;
        characteristics.forEach((characteristic) {
          var valuex = characteristic.uuid.toString();
          print("所有特征值 --- $valuex");
          print("当前值-=-=-==-"+characteristic.uuid.toString());
          if (characteristic.uuid.toString() ==
              "0000ae01-0000-1000-8000-00805f9b34fb") {
            print("匹配到正确的特征值");
            mCharacteristic = characteristic;

            const timeout = const Duration(seconds: 1);
            Timer(timeout, () {
              print("回调打印数据.....");
              //收到下位机返回蓝牙数据回调监听
              _BleDataCallback();
            });
          }
        });
      }
    });
  }

  //写入数据
  sendData() {
    //mCharacteristic   4.扫描蓝牙设备备注有介绍、6.匹配对应权限特征中给它赋值
    // mCharacteristic.write(
    //     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
    mCharacteristic.write([1]);
  }

  //获取下位机数据
  //mCharacteristic   4.扫描蓝牙设备备注有介绍、6.匹配对应权限特征中给它赋值
//_BleDataCallback 方法在6.匹配对应权限特征中 调用
  _BleDataCallback() async {
    await mCharacteristic.setNotifyValue(true);
    mCharacteristic.value.listen((value) {
      // do something with new value
      // print("我是蓝牙返回数据 - $value");
      if (value == null) {
        print("我是蓝牙返回数据 - 空！！");
        return;
      }
      List data = [];
      for (var i = 0; i < value.length; i++) {
        String dataStr = value[i].toRadixString(16);
        if (dataStr.length < 2) {
          dataStr = "0" + dataStr;
        }
        String dataEndStr = "0x" + dataStr;
        data.add(dataEndStr);
      }
      print("我是蓝牙返回数据 - $data");
    });
  }

  //断开连接
  clear() {
    device.disconnect();
  }

  //连接到设备
  toBlueDevice(String deviceName) {
    List distinctIds = allBlueNameAry.toSet().toList();
    print("我是过滤后的 蓝牙名字" + distinctIds.length.toString());
    for (var i = 0; i < distinctIds.length; i++) {
      bool isEquipment = distinctIds[i].contains(deviceName);
      print(distinctIds[i].toString());
      if (isEquipment) {
        print(distinctIds[i].toString() + "蓝牙连接成功_+_+_+_+_+_");
        ScanResult? r = scanResults[distinctIds[i]];
        device = r!.device;
        // 停止扫描
        flutterBlue.stopScan();

        // 连接蓝牙设备 以及扫描特征值
        print("连接蓝牙设备 以及扫描特征值");
        _BleDiscoverServices();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("蓝牙通讯"),
        centerTitle: true,
      ),
      body: ListView(
        children: [
          Container(
            width: 100,
            height: 40,
            color: Colors.red,
            child: InkWell(
                onTap: () {
                  //toBlueDevice("Ptalk OWS 1");
                  //print("获取蓝牙数据");
                  sendData();
                },
                child: Text("写入数据")),
          ),
          Container(
            width: 100,
            height: 40,
            color: Colors.green,
            child: InkWell(
                onTap: () {
                  toBlueDevice("Ptalk OWS 1");
                  //print("开始连接设备");
                },
                child: Text("连接到设备")),
          ),
          InkWell(
            onTap: () {
              getData();
            },
            child: Container(
              width: 100,
              height: 40,
              color: Colors.orange,
              child: Text("开始扫描"),
            ),
          ),
          InkWell(
            onTap: () {
              clear();
              print("停止扫描");
            },
            child: Container(
              width: 100,
              height: 40,
              color: Colors.green,
              child: Text("停止扫描"),
            ),
          ),
          InkWell(
            onTap: () {},
            child: Container(
              width: 100,
              height: 40,
              color: Colors.green,
              child: Text("停止扫描"),
            ),
          ),
          InkWell(
            onTap: () {},
            child: Container(
              width: 100,
              height: 40,
              color: Colors.green,
              child: Text("断开连接"),
            ),
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            child: Column(
              children: allBlueNameAry
                  .map((e) => InkWell(
                onTap: (){
                  print(e.toString());
                  toBlueDevice(e.toString());
                },
                    child: Container(
                width: 100,
                          alignment: Alignment.center,
                          height: 60,
                          color: Colors.green,
                          child: Text(""+e.toString(),style: TextStyle(color: Colors.black),),
                        ),
                  ))
                  .toList(),
            ),
          )
        ],
      ),
    );
  }
}
